package com.lishem.top100._01hash;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode.cn/problems/longest-consecutive-sequence/description/
 * <p>
 * 给定一个未排序的整数数组 nums ，找出数字连续的最长序列（不要求序列元素在原数组中连续）的长度。
 * <p>
 * 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
 * <p>
 * 示例 1：
 * <p>
 * 输入：nums = [100,4,200,1,3,2]
 * <p>
 * 输出：4
 * <p>
 * 解释：最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
 * <p>
 * 示例 2：
 * <p>
 * 输入：nums = [0,3,7,2,5,8,4,6,0,1]
 * <p>
 * 输出：9
 */
public class _3LetCode128_最长连续序列 {

    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (Integer num : nums) {
            set.add(num);
        }

        int maxLen = 0;
        for (int num : nums) {
            // 确定这个数是这一波数的最小值
            if (!set.contains(num - 1)) {
                int curNum = num;
                int curLen = 1;
                while (set.contains(curNum + 1)) {
                    curNum = curNum + 1;
                    curLen++;
                }
                maxLen = Math.max(curLen, maxLen);
            }
        }
        return maxLen;
    }


    /**
     * n * logn 解法
     */
    public int longestConsecutive1(int[] nums) {
        if (nums.length < 1) {
            return 0;
        }
        Arrays.sort(nums);
        int maxLen = 1;
        int curLen = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
            } else if (nums[i] - nums[i - 1] == 1) {
                curLen++;
                maxLen = Math.max(maxLen, curLen);
            } else {
                curLen = 1;
            }
        }
        return maxLen;
    }

    public static void main(String[] args) {
        _3LetCode128_最长连续序列 sol = new _3LetCode128_最长连续序列();
        System.out.println(sol.longestConsecutive1(new int[]{100, 4, 200, 1, 3, 2}));
        System.out.println(sol.longestConsecutive1(new int[]{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}));

        System.out.println(sol.longestConsecutive(new int[]{100, 4, 200, 1, 3, 2}));
        System.out.println(sol.longestConsecutive(new int[]{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}));
    }
}
